package com.cypher.encryptionanddecryption.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothManagerSingleton;
import com.cypher.encryptionanddecryption.fragment.BluetoothInfoListFragment;
import com.cypher.encryptionanddecryption.fragment.BluetoothTalkFloatingFragment;
import com.cypher.encryptionanddecryption.fragment.BluetoothTalkFragment;
import com.cypher.encryptionanddecryption.fragment.CommunicationFloatingFragment;
import com.cypher.encryptionanddecryption.fragment.CommunicationFragment;
import com.cypher.encryptionanddecryption.fragment.FloatingActionSearchFragment;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothUtilManager;
import com.cypher.encryptionanddecryption.fragment.MaintainListFragment;
import com.cypher.encryptionanddecryption.fragment.SettingsFragment;
import com.cypher.encryptionanddecryption.util.ProgressDialogUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RadioButton deviceBtn;
    private RadioButton talkBtn;
    private RadioButton communicationBtn;
    private RadioButton repairBtn;
    private RadioButton settingsBtn;
    public RadioButton getSettingsBtn() {
        return settingsBtn;
    }
    /**
     * 协议名称
     */
    private TextView protocolTitle;
    /**
     * 协议类型，默认为空
     */
    public Integer protocolId;
    public Integer getProtocolId() {
        return protocolId;
    }
    public void setProtocolId(Integer protocolId) {
        this.protocolId = protocolId;
    }

    private BluetoothUtilManager bluetoothUtilManager;

    // 定义蓝牙信息列表块
    private BluetoothInfoListFragment bluetoothInfoListFragment;
    // 定义蓝牙信息列表浮动按钮块
    private FloatingActionSearchFragment floatingActionSearchFragment;
    public FloatingActionSearchFragment getFloatingActionSearchFragment() {
        return floatingActionSearchFragment;
    }

    // 定义蓝牙对话框
    private BluetoothTalkFragment talkFragment;
    // 定义蓝牙对话框浮动块
    private BluetoothTalkFloatingFragment talkFloatingFragment;

    // 定义通信列表界面
    private CommunicationFragment communicationFragment;
    public CommunicationFragment getCommunicationFragment() {
        return communicationFragment;
    }
    private CommunicationFloatingFragment communicationFloatingFragment;
    public CommunicationFloatingFragment getCommunicationFloatingFragment() {
        return communicationFloatingFragment;
    }
    private SettingsFragment settingsFragment;
    public SettingsFragment getSettingsFragment() {
        return settingsFragment;
    }
    private MaintainListFragment maintainListFragment;

    private boolean isExit = false;
    // 接收zxing扫描后的结果视图
    private EditText zxingView;

    /**
     * 存放Fragment集合
     */
    private List<Fragment> fragmentList;
    /**
     * 需要添加到activity的Fragment集合
     */
    private List<Fragment> addFragmentList;

    public RadioButton getCommunicationBtn() {
        return communicationBtn;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        protocolTitle = findViewById(R.id.txt_protocol);

        ApplicationManager.getInstance().getActivities().add(this);

        getBlePermissionFromSys();

        initAllFragment();

        // 初始化按钮组
        initBtnClickListener();

        // 初始化蓝牙管理工具类
        bluetoothUtilManager = new BluetoothUtilManager(this);
        // 蓝牙管理工具类存放到单例中
        BluetoothManagerSingleton bluetoothManagerSingleton = BluetoothManagerSingleton.getInstance();
        bluetoothManagerSingleton.setActivity(this);
        bluetoothManagerSingleton.setBluetoothUtilManager(bluetoothUtilManager);

    }

    /**
     * 设置协议标题
     * @param protocol
     */
    public void setProtocolTitle(String protocol) {
        protocolTitle.setText(protocol);
    }
    /**
     * 初始化按钮监听事件
     */
    private void initBtnClickListener() {
        // 初始化集合
        addFragmentList = new ArrayList<>();
        // 初始化设备连接按钮
        deviceBtn = findViewById(R.id.device_btn);
        // 添加蓝牙列表到主界面
        View.OnClickListener deviceBtnClick = (v) -> {
            addFragmentList.clear();
            addFragmentList.add(bluetoothInfoListFragment);
            addFragmentList.add(floatingActionSearchFragment);
            showFragment(addFragmentList);
        };
        deviceBtn.setOnClickListener(deviceBtnClick);

        // 初始化对话服务按钮
        talkBtn = findViewById(R.id.talk_btn);
        // 添加对话界面到主界面
        View.OnClickListener talkBtnClick = (v) -> {
            addFragmentList.clear();
            addFragmentList.add(talkFragment);
            addFragmentList.add(talkFloatingFragment);
            showFragment(addFragmentList);
        };
        talkBtn.setOnClickListener(talkBtnClick);

        // 初始化通信列表按钮
        communicationBtn = findViewById(R.id.communication_btn);
        // 添加通信列表到主界面
        View.OnClickListener communicationBtnClick = (v) -> {
            addFragmentList.clear();
            addFragmentList.add(communicationFragment);
            addFragmentList.add(communicationFloatingFragment);
            showFragment(addFragmentList);
        };
        communicationBtn.setOnClickListener(communicationBtnClick);

        // 初始化维护模式按钮
        repairBtn = findViewById(R.id.repair_btn);
        // 添加对话界面到主界面
        View.OnClickListener repairBtnClick = (v) -> {
            addFragmentList.clear();
            addFragmentList.add(maintainListFragment);
            showFragment(addFragmentList);
        };
        repairBtn.setOnClickListener(repairBtnClick);

        // 初始化设置按钮
        settingsBtn = findViewById(R.id.settings_btn);
        // 添加设置功能到主界面
        View.OnClickListener settingsBtnClick = (v) -> {
            addFragmentList.clear();
            addFragmentList.add(settingsFragment);
            showFragment(addFragmentList);
        };
        settingsBtn.setOnClickListener(settingsBtnClick);
    }

    /**
     * 初始化所有Fragment
     */
    private void initAllFragment() {
        // 初始化Fragment存储结合
        fragmentList = new ArrayList<Fragment>();

        // 初始化蓝牙列表界面
        bluetoothInfoListFragment = new BluetoothInfoListFragment();
        floatingActionSearchFragment = new FloatingActionSearchFragment();
        // 默认展示列表为蓝牙通信列表
        getSupportFragmentManager().beginTransaction().add(R.id.bluetooth_fragment, bluetoothInfoListFragment).commitAllowingStateLoss();
        getSupportFragmentManager().beginTransaction().add(R.id.bluetooth_fragment, floatingActionSearchFragment).commitAllowingStateLoss();
        fragmentList.add(bluetoothInfoListFragment);
        fragmentList.add(floatingActionSearchFragment);

        // 初始化对话界面
        talkFragment = new BluetoothTalkFragment();
        talkFloatingFragment = new BluetoothTalkFloatingFragment();
        fragmentList.add(talkFragment);
        fragmentList.add(talkFloatingFragment);

        // 初始化通信列表界面
        communicationFragment = new CommunicationFragment();
        communicationFloatingFragment = new CommunicationFloatingFragment();
        fragmentList.add(communicationFragment);
        fragmentList.add(communicationFloatingFragment);

        maintainListFragment = new MaintainListFragment();
        fragmentList.add(maintainListFragment);

        settingsFragment = new SettingsFragment();
        fragmentList.add(settingsFragment);
    }
    /**
     * 显示Fragment
     * @param fragments
     */
    public void showFragment(List<Fragment> fragments) {
        for (Fragment fragment : fragments) {
            if (!fragment.isAdded()) {
                getSupportFragmentManager().beginTransaction().add(R.id.bluetooth_fragment, fragment).commitAllowingStateLoss();
            }
            getSupportFragmentManager().beginTransaction().show(fragment).commitAllowingStateLoss();
        }
        // 隐藏其他Fragment
        for (Fragment fragment : fragmentList) {
            // 如果需要添加列表没有初始化列表fragment则隐藏之
            if (!fragments.contains(fragment)) {
                getSupportFragmentManager().beginTransaction().hide(fragment).commitAllowingStateLoss();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播
//        bluetoothUtilManager.destroyReceiver();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 动态获取权限
     */
    public void getBlePermissionFromSys() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 102;
            String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }

    }

    /**
     * 双击退出程序
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode== KeyEvent.KEYCODE_BACK){
            final AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(this, R.style.AlertDialog);
            normalDialog.setMessage("您确认要退出应用？");
            normalDialog.setPositiveButton("确定", (DialogInterface dialog, int which) -> {
                // 结束全部activity
                for(Activity activity : ApplicationManager.getInstance().getActivities()) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }
                }
                BluetoothManagerSingleton managerSingleton = BluetoothManagerSingleton.getInstance();
                if (managerSingleton != null) {

                    BluetoothUtilManager bluetoothUtilManager = managerSingleton.getBluetoothUtilManager();
                    if (bluetoothUtilManager != null) {
                        bluetoothUtilManager.destroyThis();
                    }
                    BluetoothGattManager bluetoothGattManager = managerSingleton.getBluetoothGattManager();
                    if (bluetoothGattManager != null) {
                        // 销毁蓝牙
                        bluetoothGattManager.destroyThis();
                    }

                    managerSingleton.releaseResource();
                }
                ProgressDialogUtil.destroy();
            });
            normalDialog.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                return;
            });
            normalDialog.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 扫描条形码
     * @param text
     *      需要获取扫描返回值的视图
     */
    public void zxingScan(EditText text) {
        // 判断是否获取相机权限
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            this.zxingView = text;
//            Intent intent = new Intent(this, CaptureActivity.class);
//            startActivityForResult(intent, 0);
        } else {
            // 获取相机权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描条形码成功
        if (0 == requestCode && 1 == resultCode) {
            if (null != zxingView && null != data) {
                zxingView.setText("");
            }
        }
    }
}